<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="查找学校名称">
                <a-input v-model="queryParam.name" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="监督员查询">
               <a-select
                v-model="queryParam.user_id" placeholder="请选择" default-value="1"
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option :value="item.id" v-for="(item) in userList" :key="item.id">
                    {{item.username}}
                </a-select-option>
              </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="标签查询">
                <a-select
                v-model="queryParam.category_id" placeholder="请选择" default-value="1"
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                >
                <a-select-option :value="item.id" v-for="(item) in labelList" :key="item.id">
                    {{item.name}}
                </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:information_add2>新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        :rowKey="(record,index)=>{return index}"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" v-action:information_edit2>修改</a>
            <a-divider type="vertical"/>
            <a-popconfirm
              v-action:information_del2
              title="确定删除这个角色吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(record)"
              @cancel="cancel(record)"
            >
              <a>删除</a>
            </a-popconfirm>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @getCheckList="getCheckList"
        @getTreeList="getTreeList"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getSchoolList, AddSchool, UpdataSchool, DelSchool} from '../../../api/school'
import { getUserList, SchoolRecursion } from '../../../api/system'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import UpdataForm from './modules/UpdataForm'

const columns = [
  {
    title: '编号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '学校名称',
    dataIndex: 'name',
  },
  {
    title: '联系人',
    dataIndex: 'contract',
  },
  {
    title: '联系方式',
    dataIndex: 'phone',
  },
  {
    title: '监督员',
    dataIndex: 'user',
  },
  {
    title: '标签',
    dataIndex: 'cate',
  },
  {
    title: '区域',
    dataIndex: 'area',
  },
  {
    title: '地址',
    dataIndex: 'address',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'SystemDepartment',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
    UpdataForm
  },
  data () {
    this.columns = columns
    return {
      // 标签展示
      labelList: [],
      // 监督员展示
      userList: [],
      // 多选按钮id
      checkedList: [],
      // 树选择列表
      treeList: [],
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam, {role_type: localStorage.getItem('role_type')})
        console.log('loadData request parameters:', requestParameters)
        return getSchoolList(requestParameters)
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  created() {
    // 调用方法获取用户列表
    this.UsersGetUserList ()
    // 调用方法获取学校标签
    this.GetSchoolRecursion()
  },
  methods: {
    // 获取学校标签列表
    GetSchoolRecursion() {
      SchoolRecursion().then(res => {
        this.labelList = res.data
      })
    },
    // 获取用户数据
    UsersGetUserList () {
    getUserList().then(res => {
      // 筛选出用户列表中 role_id 为15的数据
      const result = res.data.data.filter(item => {
        return item.role_id === 15
      })
      this.userList = result
    })
  },
    // 树下拉列表
    getTreeList(value) {
      this.treeList = value
    },
    // 获取多选列表
    getCheckList(value) {
      this.checkedList = value
      console.log('------------------------------', value)
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    // 创建
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          if (values.id > 0) {
            // 修改 e.g.
            new Promise((resolve, reject) => {
              // 树选择
              values.category_id = this.treeList
              // 多选
              values.user_id = this.checkedList
              UpdataSchool(values).then(res => {
                if ( res ) {
                  resolve()
                } else {
                  console.log(333)
                  this.confirmLoading = false
                }
              }, reason => {
                  console.log(444)
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('修改成功')
            }).catch(error => {
              this.$message.info('该学校名已存在')
              this.confirmLoading = false
            })
          } else {
            // 新增
            new Promise((resolve, reject) => {
              // 树选择
              values.category_id = this.treeList
              // 多选
              values.user_id = this.checkedList
              AddSchool(values).then(res => {
                  if( res ) {
                    resolve()
                  } else {
                    this.confirmLoading = false
                  }
              })
            }).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('新增成功')
            })
          }
        } else {
          console.log(errors)
          this.confirmLoading = false
        }
      })
    },
     // 删除
    confirm(e) {
      const form = this.$refs.createModal.form
      console.log(e);
      DelSchool({id: e.id}).then(res => {
        // 重置表单数据
        form.resetFields()
        // 刷新表格
        this.$refs.table.refresh()
        this.$message.success('删除成功');
      }).catch(error => {
        console.log('-------------error------------', error)
      })
    },
    cancel(e) {
      console.log(e);
      this.$message.error('已取消');
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 启用 
    handleEnable (record) {
      
    },
    // 禁用
    handleDisable (record) {

    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    // 重置
    reset () {
      const form = this.$refs.createModal.form
      this.queryParam = {}
        // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    // 搜素模糊查询
    filterOption(input, option) {
      return (
    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>
